<template>
  <div class="app-container">
    <!-- 搜索和操作区域保持不变 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="食谱名称" prop="recipeName">
        <el-input
          v-model="queryParams.recipeName"
          placeholder="请输入食谱名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      :data="recipeList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column prop="recipeName" label="食谱名称" align="center" />
      <el-table-column prop="userName" label="咨询人" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template #default="scope">
          {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        prop="consultBody"
        label="咨询内容"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="consultTime"
        label="咨询时间"
        align="center"
        width="160px"
      >
        <template #default="scope">
          {{ parseTime(scope.row.consultTime, "{y}-{m}-{d} {h}:{m}:{s}") }}
        </template>
      </el-table-column>
      <el-table-column prop="suggestBody" label="建议内容" align="center" />
      <el-table-column prop="feedbackBody" label="反馈内容" align="center" />
      <el-table-column label="操作" align="center" width="180px">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleDetail(scope.row)"
            v-hasPermi="['manage:recipe:list']"
            >查看</el-button
          >
          <el-button
            size="small"
            type="success"
            @click="handleSuggest(scope.row)"
            v-hasPermi="['manage:recipe:edit']"
            v-if="
              scope.row.suggestBody === null || scope.row.suggestBody === ''
            "
            >建议</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食谱管理对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="recipeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食谱名称" prop="recipeName">
          <el-input v-model="form.recipeName" placeholder="请输入食谱名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看食谱管理对话框 -->
    <el-dialog :title="title" v-model="detailOpen" width="600px" append-to-body>
      <el-tabs v-model="activeDetailTab" type="card" class="detail-tabs">
        <!-- 早餐食谱 -->
        <el-tab-pane label="早餐" name="breakfast">
          <div
            v-for="(item, index) in detailRecipe.breakfastRecipe"
            :key="`breakfast-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 午餐食谱 -->
        <el-tab-pane label="午餐" name="lunch">
          <div
            v-for="(item, index) in detailRecipe.lunchRecipe"
            :key="`lunch-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 晚餐食谱 -->
        <el-tab-pane label="晚餐" name="dinner">
          <div
            v-for="(item, index) in detailRecipe.dinnerRecipe"
            :key="`dinner-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <el-tab-pane label="建议" name="suggestion">
          <el-form-item label="建议内容" class="suggest-input">
            <el-input
              type="textarea"
              :rows="5"
              v-model="detailRecipe.suggestBody"
              placeholder="无建议内容"
              resize="none"
              readonly
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 新增建议编辑对话框 -->
    <el-dialog
      title="食谱建议"
      v-model="suggestOpen"
      width="600px"
      append-to-body
    >
      <el-form :model="suggestRecipe" label-width="80px">
        <el-tabs
          v-model="activeSuggestTab"
          type="card"
          class="detail-tabs"
          @tab-click="closeAllPopovers"
        >
          <!-- 早餐食谱 -->
          <el-tab-pane label="早餐" name="breakfast">
            <div
              v-for="(item, index) in suggestRecipe.breakfastRecipe"
              :key="`breakfast-${index}`"
              class="recipe-item"
            >
              <el-form-item label="食材名称">
                <el-input
                  v-model="item.foodName"
                  placeholder="请输入食材名称"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-popover
                  placement="top-end"
                  :width="400"
                  trigger="manual"
                  :visible="item.popoverVisible"
                >
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="item.remark"
                  />
                  <div style="text-align: right; margin-top: 8px">
                    <el-button size="small" @click="closePopover(item)"
                      >取 消</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="confirmEdit(item)"
                      >确 定</el-button
                    >
                  </div>
                  <template #reference>
                    <el-input
                      v-model="item.remark"
                      placeholder="请输入备注"
                      @click="openPopover(item)"
                    >
                    </el-input>
                  </template>
                </el-popover>
              </el-form-item>
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="removeRecipeItem('breakfast', index)"
                class="delete-btn"
                >删除</el-button
              >
            </div>
            <div class="add-btn-container">
              <el-button
                type="primary"
                size="small"
                @click="addRecipeItem('breakfast')"
                icon="Plus"
                circle
              />
            </div>
          </el-tab-pane>

          <!-- 午餐食谱 -->
          <el-tab-pane label="午餐" name="lunch">
            <div
              v-for="(item, index) in suggestRecipe.lunchRecipe"
              :key="`lunch-${index}`"
              class="recipe-item"
            >
              <el-form-item label="食材名称">
                <el-input
                  v-model="item.foodName"
                  placeholder="请输入食材名称"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-popover
                  placement="top-end"
                  :width="400"
                  trigger="manual"
                  :visible="item.popoverVisible"
                >
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="item.remark"
                  />
                  <div style="text-align: right; margin-top: 8px">
                    <el-button size="small" @click="closePopover(item)"
                      >取 消</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="confirmEdit(item)"
                      >确 定</el-button
                    >
                  </div>
                  <template #reference>
                    <el-input
                      v-model="item.remark"
                      placeholder="请输入备注"
                      @click="openPopover(item)"
                    >
                    </el-input>
                  </template>
                </el-popover>
              </el-form-item>
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="removeRecipeItem('lunch', index)"
                class="delete-btn"
                >删除</el-button
              >
            </div>
            <div class="add-btn-container">
              <el-button
                type="primary"
                size="small"
                @click="addRecipeItem('lunch')"
                icon="Plus"
                circle
              />
            </div>
          </el-tab-pane>

          <!-- 晚餐食谱 -->
          <el-tab-pane label="晚餐" name="dinner">
            <div
              v-for="(item, index) in suggestRecipe.dinnerRecipe"
              :key="`dinner-${index}`"
              class="recipe-item"
            >
              <el-form-item label="食材名称">
                <el-input
                  v-model="item.foodName"
                  placeholder="请输入食材名称"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-popover
                  placement="top-end"
                  :width="400"
                  trigger="manual"
                  :visible="item.popoverVisible"
                >
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="item.remark"
                  />
                  <div style="text-align: right; margin-top: 8px">
                    <el-button size="small" @click="closePopover(item)"
                      >取 消</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="confirmEdit(item)"
                      >确 定</el-button
                    >
                  </div>
                  <template #reference>
                    <el-input
                      v-model="item.remark"
                      placeholder="请输入备注"
                      @click="openPopover(item)"
                    >
                    </el-input>
                  </template>
                </el-popover>
              </el-form-item>
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="removeRecipeItem('dinner', index)"
                class="delete-btn"
                >删除</el-button
              >
            </div>
            <div class="add-btn-container">
              <el-button
                type="primary"
                size="small"
                @click="addRecipeItem('dinner')"
                icon="Plus"
                circle
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="建议" name="suggestion">
            <el-form-item label="建议内容" class="suggest-input">
              <el-input
                type="textarea"
                :rows="5"
                v-model="suggestRecipe.suggestBody"
                placeholder="请输入建议内容"
                resize="none"
                :maxlength="1000"
                show-word-limit
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSuggest">提交</el-button>
          <el-button @click="suggestOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Suggest">
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe, batchUpdateRecipe } from "@/api/manage/recipe"
import { listConsult, getConsult, delConsult, addConsult, updateConsult } from "@/api/manage/consult"
import { useRoute } from "vue-router"

// 监听 URL 参数变化
const route = useRoute();

const { proxy } = getCurrentInstance()
const recipeList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const detailRecipe = ref({})
const activeDetailTab = ref('breakfast')

const suggestOpen = ref(false) // 新增建议对话框状态
// 修改初始化activeSuggestTab
const activeSuggestTab = ref('suggestion') // 默认激活建议tab
const suggestRecipe = ref({}) // 新增建议数据

const data = reactive({
  form: {
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recipeName: null,
    isVerifying: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询食谱管理列表 */
function getList () {
  loading.value = true
  queryParams.value.isVerifying = 'consult'
  listRecipe(queryParams.value).then(response => {
    recipeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    recipeId: null,
    recipeName: null,
    breakfastRecipe: null,
    lunchRecipe: null,
    dinnerRecipe: null,
    userId: null,
    createTime: null,
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  }
  proxy.resetForm("recipeRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  // ids为多选框选中的未通过审批的id
  ids.value = selection.map(item => {
    if (item.verifyFlag === 0) {
      return item.recipeId
    }
  })
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleAllVerify () {
  proxy.$modal.confirm('确定要一键审批选中的食谱吗？').then(function () {
    return batchUpdateRecipe(ids.value)
  }).then(res => {
    getList()
    if (res.code === 200) {
      proxy.$modal.msgSuccess("一键审批成功")
    }
  }).catch(() => { })
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = "添加食谱管理"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _recipeId = row.recipeId || ids.value
  getRecipe(_recipeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改食谱管理"
  })
}

/** 查看按钮操作 */
function handleDetail (recipe) {
  const _recipeId = recipe.recipeId || ids.value
  getRecipe(_recipeId).then(response => {
    detailRecipe.value = response.data
    // 将json转换为数组
    detailRecipe.value.breakfastRecipe = JSON.parse(detailRecipe.value.breakfastRecipe || '[]')
    detailRecipe.value.lunchRecipe = JSON.parse(detailRecipe.value.lunchRecipe || '[]')
    detailRecipe.value.dinnerRecipe = JSON.parse(detailRecipe.value.dinnerRecipe || '[]')
    // 确保建议内容被正确赋值
    detailRecipe.value.suggestBody = response.data.suggestBody || ''
    // 重置activeTab为默认值
    activeDetailTab.value = 'breakfast'
    detailOpen.value = true
    title.value = "食谱详情"
  })
}

/** 提交按钮 */
function submitForm () {
  proxy.$refs["recipeRef"].validate(valid => {
    if (valid) {
      if (form.value.recipeId != null) {
        updateRecipe(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 提取数据
        const recipeData = {}
        recipeData.recipeName = form.value.recipeName
        recipeData.remark = form.value.remark
        // 移除 popoverVisible 字段并转换为 JSON 字符串
        recipeData.breakfastRecipe = JSON.stringify(
          form.value.breakfastList.map(item => {
            const { popoverVisible, ...rest } = item // 解构赋值，移除 popoverVisible
            return rest
          })
        )
        recipeData.lunchRecipe = JSON.stringify(
          form.value.lunchList.map(item => {
            const { popoverVisible, ...rest } = item // 解构赋值，移除 popoverVisible
            return rest
          })
        )
        recipeData.dinnerRecipe = JSON.stringify(
          form.value.dinnerList.map(item => {
            const { popoverVisible, ...rest } = item // 解构赋值，移除 popoverVisible
            return rest
          })
        )
        addRecipe(recipeData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _recipeIds = row.recipeId || ids.value
  const delName = _recipeIds.length >= 1 ? '选中的食谱' : row.recipeName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delRecipe(_recipeIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

// 新增进食记录
function handleAddItem (mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.push({})
  } else if (mealType === 'lunch') {
    form.value.lunchList.push({})
  } else {
    form.value.dinnerList.push({})
  }
}

// 删除进食记录
function handleRemoveItem (index, mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.splice(index, 1)
  } else if (mealType === 'lunch') {
    form.value.lunchList.splice(index, 1)
  } else {
    form.value.dinnerList.splice(index, 1)
  }
}

// 存储旧数据的变量
const oldRecipe = ref(null)

/** 建议按钮操作 */
function handleSuggest (row) {
  // 存储旧数据
  oldRecipe.value = JSON.parse(JSON.stringify(row))
  suggestRecipe.value = JSON.parse(JSON.stringify(row))
  // 将json转换为数组
  suggestRecipe.value.breakfastRecipe = JSON.parse(suggestRecipe.value.breakfastRecipe || '[]')
  suggestRecipe.value.lunchRecipe = JSON.parse(suggestRecipe.value.lunchRecipe || '[]')
  suggestRecipe.value.dinnerRecipe = JSON.parse(suggestRecipe.value.dinnerRecipe || '[]')

  // 初始化popoverVisible为false
  const mealTypes = ['breakfastRecipe', 'lunchRecipe', 'dinnerRecipe']
  for (const mealType of mealTypes) {
    if (suggestRecipe.value[mealType] && Array.isArray(suggestRecipe.value[mealType])) {
      for (const item of suggestRecipe.value[mealType]) {
        item.popoverVisible = false
      }
    }
  }

  // 重置activeTab为默认值
  activeSuggestTab.value = 'breakfast'
  suggestOpen.value = true
}

/** 提交建议 */
function submitSuggest () {
  // 检查建议内容是否为空
  if (!suggestRecipe.value.suggestBody?.trim()) {
    proxy.$modal.msgWarning("建议内容不能为空")
    return
  }

  // 检查是否有修改
  const hasChanges = () => {
    // 检查建议内容是否修改
    if (suggestRecipe.value.suggestBody !== oldRecipe.value.suggestBody) {
      return true
    }

    // 检查食谱内容是否修改
    const mealTypes = ['breakfastRecipe', 'lunchRecipe', 'dinnerRecipe']
    for (const mealType of mealTypes) {
      const oldItems = JSON.parse(oldRecipe.value[mealType] || '[]')
      const newItems = suggestRecipe.value[mealType].filter(item =>
        item.foodName || item.remark
      )

      if (oldItems.length !== newItems.length) {
        return true
      }

      for (let i = 0; i < newItems.length; i++) {
        if (newItems[i].foodName !== oldItems[i]?.foodName ||
          newItems[i].remark !== oldItems[i]?.remark) {
          return true
        }
      }
    }

    return false
  }

  if (!hasChanges()) {
    proxy.$modal.msgWarning("您还未进行任何修改操作")
    return
  }

  // 过滤掉空数据行
  const filterEmptyItems = (items) => {
    return items.filter(item => item.foodName || item.remark)
  }

  // 构造提交数据
  const recipe = oldRecipe.value
  const consult = {
    oldRecipeId: oldRecipe.value.recipeId,
    userId: oldRecipe.value.userId,
    suggestBody: suggestRecipe.value.suggestBody
  }
  const data = {
    recipe: recipe,
    consult: consult,
    newBreakFastRecipe: JSON.stringify(
      filterEmptyItems(suggestRecipe.value.breakfastRecipe).map(item => {
        const { popoverVisible, originalRemark, ...rest } = item
        return rest
      })
    ),
    newLunchRecipe: JSON.stringify(
      filterEmptyItems(suggestRecipe.value.lunchRecipe).map(item => {
        const { popoverVisible, originalRemark, ...rest } = item
        return rest
      })
    ),
    newDinnerRecipe: JSON.stringify(
      filterEmptyItems(suggestRecipe.value.dinnerRecipe).map(item => {
        const { popoverVisible, originalRemark, ...rest } = item
        return rest
      })
    )
  }

  // 检查是否有实际数据
  const hasData =
    data.newBreakFastRecipe !== '[]' ||
    data.newLunchRecipe !== '[]' ||
    data.newDinnerRecipe !== '[]' ||
    data.consult.suggestBody

  if (!hasData) {
    proxy.$modal.msgWarning("请至少填写一项内容")
    return
  }

  console.log(data)

  addConsult(data).then(response => {
    suggestOpen.value = false
    proxy.$modal.msgSuccess("提交成功")
    getList()
  })
}

// 新增食谱项
function addRecipeItem (mealType) {
  if (!suggestRecipe.value[`${mealType}Recipe`]) {
    suggestRecipe.value[`${mealType}Recipe`] = []
  }
  suggestRecipe.value[`${mealType}Recipe`].push({
    foodName: '',
    remark: '',
    popoverVisible: false
  })
}

// 删除食谱项
function removeRecipeItem (mealType, index) {
  suggestRecipe.value[`${mealType}Recipe`].splice(index, 1)
}

function openPopover (row) {
  if (!row.popoverVisible) {  // 防止重复打开
    row.popoverVisible = true
    // 保存当前备注内容作为原始值
    row.originalRemark = row.remark
  }
};

function confirmEdit (row) {
  row.popoverVisible = false
  // 确认编辑后，更新原始值
  row.originalRemark = row.remark
};

// 关闭 Popover
function closePopover (row) {
  row.popoverVisible = false
  // 恢复为原始值而不是清空
  row.remark = row.originalRemark
};

// 关闭所有popover
function closeAllPopovers () {
  const mealTypes = ['breakfastRecipe', 'lunchRecipe', 'dinnerRecipe']
  for (const mealType of mealTypes) {
    if (suggestRecipe.value[mealType] && Array.isArray(suggestRecipe.value[mealType])) {
      for (const item of suggestRecipe.value[mealType]) {
        item.popoverVisible = false
      }
    }
  }
}

// 通过 URL 获取查询参数
onMounted(() => {
  const params = new URLSearchParams(window.location.search);
  if (params.has('recipeName')) {
    queryParams.value.recipeName = params.get('recipeName');
  }
  handleQuery(); // 执行查询
});

// 监听 recipeName 参数变化
watch(() => route.query.recipeName, (newRecipeName) => {
  if (newRecipeName !== undefined) {
    queryParams.value.recipeName = newRecipeName;
    queryParams.value.pageNum = 1; // 重置页码
    handleQuery(); // 重新执行查询
  }
});

getList()
</script>

<style lang="scss" scoped>
.recipe-item {
  position: relative;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
}

.recipe-item .el-form-item {
  margin-bottom: 15px;
  width: calc(100% - 70px);
}

.delete-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.add-btn-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.meal-detail {
  padding: 10px;
}

.meal-item {
  margin-bottom: 10px;
}

.meal-item p {
  margin: 5px 0;
  font-size: 14px;
}

.suggest-input {
  margin: 20px;
}

.suggest-input :deep(.el-form-item__content) {
  width: 100%;
}
</style>